//
//  IMViewController.m
//  IMQuickSearch
//
//  Created by Ben Gordon on 12/13/13.
//  Copyright (c) 2013 Intermark. All rights reserved.
//

#import "SearchUniversityViewController.h"
#import "UniversityDetailViewController.h"
#import "University.h"
#import "Unit.h"
#import <BmobSDK/Bmob.h>

@interface SearchUniversityViewController()
@property (weak, nonatomic) IBOutlet UIImageView *searchImageView;

@property (nonatomic,strong) NSMutableArray* unitsArray; // 临时在本页面存放招生单元的数组
@property (nonatomic,strong) University* university;     // 临时在本页面存放university

@end

@implementation SearchUniversityViewController

static const int BMOBQUERY_LIMIT = 1000;  // Bmob 单次查询数据数目的上限

// 重写getter，防止addObject的时候该属性为nil
-( NSMutableArray* ) universityArray
{
    if (!_universityArray) { _universityArray = [[ NSMutableArray alloc ] init ]; };
    return _universityArray;
}
// 重写getter，防止addObject的时候该属性为nil
-( NSMutableArray* ) unitsArray
{
    if (!_unitsArray) { _unitsArray = [[ NSMutableArray alloc ] init ]; };
    return _unitsArray;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 设置返回按钮文字
    // Set this in every view controller so that the back button displays back instead of the root view controller name
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    // 设置分割线样式
    self.searchTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.searchTableView.separatorColor = [UIColor colorWithRed:236/255.0 green:208/255.0 blue:191/255.0 alpha:1 ];
    
    // 初始化搜索
    [self setUpQuickSearch];
     self.FilteredResults = [self.QuickSearch filteredObjectsWithValue:nil];
    [self filterResults];
    
    
    // 设置 搜索按钮
    self.searchImageView.userInteractionEnabled = true;
    UITapGestureRecognizer *searchImageViewTapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(searchImageViewTouch:)];
    searchImageViewTapGesture.numberOfTapsRequired = 1;
    searchImageViewTapGesture.enabled =YES;
    [searchImageViewTapGesture delaysTouchesBegan];
    [searchImageViewTapGesture cancelsTouchesInView];
    [self.searchImageView addGestureRecognizer:searchImageViewTapGesture ];
    
}

// 处理 搜索按钮的点击事件
-(void)searchImageViewTouch:(UIGestureRecognizer*) recognizer
{
    // 如果没有从服务端读取出大学的数组
    if( ![self.universityArray count ] ){
        
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"抱歉，网络不给力，请稍候再试" message:nil delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [alter show];
        
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Set Up the Quick Search
- (void)setUpQuickSearch {
    // Create Filters
    IMQuickSearchFilter *peopleFilter = [IMQuickSearchFilter filterWithSearchArray:self.universityArray keys:@[@"name"]];
//    IMQuickSearchFilter *animalFilter = [IMQuickSearchFilter filterWithSearchArray:self.Animals keys:@[@"name"]];
    
    // Init IMQuickSearch with those Filters
    self.QuickSearch = [[IMQuickSearch alloc] initWithFilters:@[peopleFilter]];
}


#pragma mark - Filter the Quick Search
- (void)filterResults {
    // Asynchronously && BENCHMARK TEST
    NSLog(@"S");
    [self.QuickSearch asynchronouslyFilterObjectsWithValue:self.searchTextField.text completion:^(NSArray *filteredResults) {
        NSLog(@"E");
        [self updateTableViewWithNewResults:filteredResults];
    }];
    
    // Synchronously
    //[self updateTableViewWithNewResults:[self.QuickSearch filteredObjectsWithValue:self.searchTextField.text]];
}

- (void)updateTableViewWithNewResults:(NSArray *)results {
    self.FilteredResults = results;
    [self.searchTableView reloadData];
}

//-------------------------------------------------------------

#pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.FilteredResults.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellId" forIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"CellId"];
       
    }
    // 这里设置cell的选中样式，否则该tableView点击后不会有变暗的选中指示（其他的表格不需要做这个设置，暂不清楚原因）
    cell.selectionStyle = UITableViewCellStyleValue1;
    
    // Set Content
    id contentObject = self.FilteredResults[indexPath.row];
    NSString *title;
    if ([contentObject isKindOfClass:[University class]]) {
        title = [(University *)contentObject name ];
    }
    cell.textLabel.text = title;
    
    return cell;
}

// 设置选中某行的处理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if( 0 == indexPath.section )
    {
//        self.university = [self.universityArray objectAtIndex:indexPath.row];
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSLog(@"university name : %@ ", cell.textLabel.text );
        
        if ( cell.textLabel.text.length ) {
            NSString* text = cell.textLabel.text;
            for ( University* selectedUniversity in self.universityArray ) {
                if ( [ selectedUniversity.name isEqualToString:text ]) {
                    self.university = selectedUniversity;
                }
            }
        }
        
        // 清空数组
        [ self.unitsArray removeAllObjects ];
        
        // Bmob查询, 查询招生单元的数组
        // 通过relatedTo 查询关联来查
        BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Unit"];
        bquery.limit = BMOBQUERY_LIMIT;
        BmobObject *universityObj = [BmobObject objectWithoutDatatWithClassName:@"University" objectId:self.university.objectId ];
        [bquery whereObjectKey:@"unit" relatedTo:universityObj];
        [bquery orderByAscending:@"createdAt"];
        [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            
            for (BmobObject *obj in array) {
                Unit* unit = [[ Unit alloc ] initWithBmobObject:obj];
                [ self.unitsArray addObject:unit ];
            }
            // 跳转页面
            [ self performSegueWithIdentifier:@"searchToUniversityDetail" sender:self.university ];
            
        }];
        
    }else
    {
        NSLog( @"You chosed section unknown " );
    }
    
}

//
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ( [segue.destinationViewController isKindOfClass:[ UniversityDetailViewController class]] ) {
        if ([segue.identifier isEqualToString:@"searchToUniversityDetail"]) {
            
            UniversityDetailViewController* udVC = (UniversityDetailViewController*) segue.destinationViewController;
            udVC.university = [[ University alloc ] initWithUniversity:sender ];
            udVC.unitsArray = self.unitsArray;
            
        }
    }
}


//-------------------------------------------------------------

#pragma mark - TextField Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    [self performSelector:@selector(filterResults) withObject:nil afterDelay:0.07];
    return YES;
}

@end
